package com.zhx.core.validate.sms;

import com.zhx.core.common.constants.SecurityConstants;
import com.zhx.core.common.properties.SecurityProperties;
import com.zhx.core.validate.code.ValidateCode;
import com.zhx.core.validate.code.ValidateCodeException;
import com.zhx.core.validate.code.ValidateCodeProcessor;
import com.zhx.core.validate.image.ImageCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * ValidateCodeFilter
 *
 * 在springsecurity 中加入自定义的filter
 *
 * 继承 OncePerRequestFilter 此过滤器可以保证在spring调起的时候这个filter只会被注册一次
 *
 * 实现 InitializingBean 接口  这个接口可以提供一个重写的方法 这个方法可以保证在资源加载完毕之后才会加载重写的方法
 *
 * 在Filter 中尽量不要用注入  因为注入的时候可能会溢出  filter 不是 spring本身的资源  是一个请求的最外层  拦截器才是spring的
 *
 * Created by zhanghaixuan on 2017/11/2.
 */
public class SmsCodeFilter extends OncePerRequestFilter implements InitializingBean{

    private AuthenticationFailureHandler myAuthentionFailedHandler;

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    private Set<String> urls = new HashSet<>();

    private SecurityProperties securityProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {
        /**
         * 首先继续实现父类的方法
         */
        super.afterPropertiesSet();

        /**
         * 将需要拦截的urls变成 Set
         */
        String urlStr = securityProperties.getValideDateCode().getSmsCode().getUrls();

        if(StringUtils.isNotBlank(urlStr)){
            String[] strings = StringUtils.splitByWholeSeparatorPreserveAllTokens(urlStr, ",");

            for(String s:strings){
                urls.add(s);
            }
        }

        urls.add(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        boolean action = false;

        for(String url:urls){
            if(antPathMatcher.match(url,request.getRequestURI())){
                action = true;
            }
        }

        if(action && StringUtils.equalsIgnoreCase("POST",request.getMethod())){
            try{
                 validate(new ServletWebRequest(request));
            } catch(ValidateCodeException e){
                myAuthentionFailedHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }else{
            filterChain.doFilter(request,response);
        }
    }


    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        ValidateCode codeInSession = (ValidateCode) sessionStrategy.getAttribute(request,
                ValidateCodeProcessor.SESSION_KEY_PREFIX+"SMS");

        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "smsCode");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }

        if(codeInSession == null){
            throw new ValidateCodeException("验证码不存在");
        }

        if(codeInSession.isExpried()){
            sessionStrategy.removeAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX+"SMS");
            throw new ValidateCodeException("验证码已过期");
        }

        if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }

        sessionStrategy.removeAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX+"SMS");
    }

    public AuthenticationFailureHandler getMyAuthentionFailedHandler() {
        return myAuthentionFailedHandler;
    }

    public void setMyAuthentionFailedHandler(AuthenticationFailureHandler myAuthentionFailedHandler) {
        this.myAuthentionFailedHandler = myAuthentionFailedHandler;
    }

    public SessionStrategy getSessionStrategy() {
        return sessionStrategy;
    }

    public void setSessionStrategy(SessionStrategy sessionStrategy) {
        this.sessionStrategy = sessionStrategy;
    }

    public Set<String> getUrls() {
        return urls;
    }

    public void setUrls(Set<String> urls) {
        this.urls = urls;
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
